package cn.firecode.data_collect.utils;

import cn.firecode.data_collect.domain.entity.ForceRealtime;
import lombok.extern.slf4j.Slf4j;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class FreeChartUtil {
    public String getChart(List<ForceRealtime> list, String fileName, String filePath){

        log.info("开始创建缩略图......:"+list.size()+"file:"+filePath+File.separator+fileName+".jpg");
        File lineChart = new File( filePath+File.separator+fileName+".jpg" );

        try {
            lineChart.createNewFile();
        } catch (IOException e) {
            log.error("create line chart file failed");
        }

        StandardChartTheme chartTheme = new StandardChartTheme("CN");


        DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset();

        for(ForceRealtime force : list){
            line_chart_dataset.addValue( force.getForce().getZ() , fileName , String.valueOf(force.getId() ));
        }

        JFreeChart lineChartObject = ChartFactory.createLineChart(
                "Force z data","time",
                "Force /N",
                line_chart_dataset, PlotOrientation.VERTICAL,
                true,true,false);
        lineChartObject.setBackgroundImageAlpha(0.0f);
        lineChartObject.setBackgroundPaint(Color.WHITE);
        lineChartObject.getLegend().setBackgroundPaint(Color.white);
        lineChartObject.getPlot().setBackgroundPaint(Color.white);
        lineChartObject.getCategoryPlot().setRangeGridlinePaint(Color.black);

        int width = 500; /* Width of the image */
        int height = 375; /* Height of the image */
        log.info("生成缩略图：  "+lineChart.getAbsolutePath());
        try {
            ChartUtilities.saveChartAsJPEG(lineChart ,lineChartObject, width ,height);
        } catch (IOException e) {
            log.error("创建缩略图失败:"+e.getMessage());
        }
        return lineChart.getAbsolutePath();


    }
}
